/**
	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package br.biofoco.p2p.rpc;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.biofoco.p2p.rpc.http.HttpTransportServer;
import br.biofoco.p2p.rpc.messaging.CommandHandler;
import br.biofoco.p2p.rpc.messaging.Transport;
import br.biofoco.p2p.rpc.messaging.TransportClient;
import br.biofoco.p2p.rpc.rest.RestTransportServer;
import br.biofoco.p2p.rpc.tcp.TcpTransportServer;

import com.google.common.collect.Maps;

public class TransportManager {

	private static final Logger LOGGER = LoggerFactory.getLogger(TransportManager.class);
	private Map<Protocol,Transport> transports = Maps.newEnumMap(Protocol.class);
	private CommandHandler commandHandler;
	
	public void registerTransport(EndPoint e) {
		LOGGER.debug("creating transport server");		
		switch (e.getProtocol()) {
			case TCP: transports.put(e.getProtocol(), new TcpTransportServer(e.getPort())); break;
			case REST: transports.put(e.getProtocol(), new RestTransportServer(e.getPort())); break;
			case HTTP: transports.put(e.getProtocol(), new HttpTransportServer(e.getPort())); break;
		}
	}
	
	public void startAll() {
		for (Transport t : transports.values()) {
			try {
				if (!t.isActive()) 
					t.start();
			} catch (Exception e) {
				LOGGER.error(e.getMessage());
			}
		}
	}
	
	public void stopAll() {
		for (Transport t : transports.values()) {
			try {
				if (t.isActive())
					t.stop();
			} catch (Exception e) {
				LOGGER.error(e.getMessage());
			}
		}
	}

	public void setCommandHandler(CommandHandler commandHandler) {
		this.commandHandler = commandHandler;
		
		for (Transport transport : transports.values()) {
			transport.setCommandHandler(commandHandler);
		}		
	}

	public TransportClient getTransportClient(Protocol protocol, EndPoint endpoint) throws Exception {
		return transports.get(protocol).createClient(endpoint);
	}
}
